<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>
      <a href="/main">首页</a>
    </el-breadcrumb-item>
    <el-breadcrumb-item>心理知识管理</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 搜索框 -->
  <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
    <el-form-item label="文章名">
      <el-input v-model="queryInfo.title" placeholder="请输入文章名" clearable @clear="queryDataList" />
    </el-form-item>
    <el-form-item label="选择作者">
      <el-select v-model="queryInfo.counselorId" placeholder="请选择咨询师作者" clearable @clear="queryDataList">
        <el-option v-for="item in counselorList" :key="item.id" :label="item.counselorName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="large" @click="queryDataList">搜索</el-button>
      <el-button type="primary" size="large" @click="add">新增</el-button>
      <el-button type="danger" size="large" @click="batchremove">批量删除</el-button>
    </el-form-item>
  </el-form>

  <!-- 表格 -->
  <el-table :data="dataList" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="ID" align="center"></el-table-column>
    <el-table-column prop="title" label="文章名" align="center"></el-table-column>
    <el-table-column prop="intro" label="文章简介" align="center"></el-table-column>
    <el-table-column prop="counselorId" label="咨询师ID" align="center"></el-table-column>
    <el-table-column prop="briefImageUrl" label="缩略图" width="125px">
      <template #default="scope">
        <el-image style="width: 100px; height: 100px;text-align:center;"
                  :src="'http://localhost:8080/sfzy/' + scope.row.briefImageUrl"
                  fit="contain"></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" align="center" width="200px">
      <template #default="scope">
        {{ formatDateTime(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column label="状态" align="center">
      <template #default="scope">
        <el-tag :type="scope.row.del === 0 ? 'success' : 'danger'">
          {{ statusMap[scope.row.del] }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="300" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
        <el-button type="primary" size="small" @click="show(scope.row.content)">查看详细内容</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <div class="demonstration"></div>
    <el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
                   :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 新增/编辑弹窗 -->
  <el-dialog :title="title1" v-model="dialogFormVisible" width="850" @close="cancle">
    <el-form :model="cwData" label-width="100">
      <el-form-item label="文章标题">
        <el-input v-model="cwData.title" autocomplete="off" placeholder="文章名"></el-input>
      </el-form-item>
      <el-form-item label="文章简介">
        <el-input v-model="cwData.intro" placeholder="请输入文章简介"></el-input>
      </el-form-item>
      <el-form-item label="咨询师作者">
        <el-select v-model="cwData.counselorId" placeholder="请选择咨询师作者" clearable>
          <el-option v-for="item in counselorList" :key="item.id" :label="item.counselorName"
                     :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="缩略图">
        <el-upload :action="uploadUrl" :on-success="handleUploadSuccess" :show-file-list="false">
          <el-icon style="height: 128px; width: 128px; border: 1px dashed #DCDFE6; color: #DCDFE6;">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容详情" prop="content">
        <el-input v-model="cwData.content" autosize type="textarea" placeholder="请输入文章内容详情" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 详情弹窗 -->
  <el-dialog title="查看详细内容" v-model="dialogFormVisible1" width="600px">
    <div class="detail-content">{{ detailContent }}</div>
    <template #footer>
      <el-button @click="dialogFormVisible1 = false">关闭</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import {
  reactive,
  ref,
  getCurrentInstance,
  onMounted
} from 'vue';

import {
  ElMessage,
  ElMessageBox
} from 'element-plus';

import { Plus } from '@element-plus/icons-vue'

// 格式化日期时间（用于展示后端返回的createTime）
const formatDateTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 总条数
const total = ref(0)

// 查询参数（移除createTime相关）
const queryInfo = reactive({
  id: '',
  title: '',
  intro: '',
  briefImageUrl: '',
  content: '',
  del: '',
  counselorId: '',
  pageNum: 1,
  pageSize: 10
})

// 状态映射
const statusMap = {
  0: '正常',
  1: '已删除',
};

// 文章列表数据
const dataList = ref([])
// 咨询师列表
const counselorList = ref([]);
// 上传地址
const uploadUrl = ref('http://localhost:8080/sfzy/upload');
// axios实例
const axios = getCurrentInstance().appContext.config.globalProperties.axios;

// 查询文章列表
const queryDataList = () => {
  axios.get('mindKnowledge/page', { params: queryInfo })
      .then((resp) => {
        if ('resp.code === 200') {
          dataList.value = resp.list;
          total.value = resp.total;
        } else {
          ElMessage.error('查询失败：' + resp.message)
        }
      }).catch(err => {
    ElMessage.error('查询接口请求失败：' + err.message)
  })
}

// 弹窗相关
const title1 = ref('')
const dialogFormVisible = ref(false)

// 查询咨询师列表
const queryCounselorList = () => {
  axios.get('counselor')
      .then((resp) => {
        if (resp.code === 200) {
          counselorList.value = resp.data || resp.list;
        } else {
          ElMessage.error('获取咨询师列表失败：' + resp.message)
        }
      }).catch(err => {
    ElMessage.error('咨询师列表接口请求失败：' + err.message)
  })
}

onMounted(() => {
  queryDataList()
  queryCounselorList()
})

// 分页处理
const handleSizeChange = (val) => {
  queryInfo.pageSize = val;
  queryDataList()
}
const handleCurrentChange = (val) => {
  queryInfo.pageNum = val;
  queryDataList()
}

// 表单数据（移除createTime字段）
const cwData = ref({
  id: '',
  title: '',
  intro: '',
  briefImageUrl: '',
  content: '',
  counselorId: '',
  del: 0
})

// 新增
const add = () => {
  title1.value = '新增'
  dialogFormVisible.value = true
  // 初始化表单（不含createTime）
  cwData.value = {
    id: '',
    title: '',
    intro: '',
    briefImageUrl: '',
    content: '',
    counselorId: '',
    del: 0
  }
}

// 取消
const cancle = () => {
  dialogFormVisible.value = false
}

// 编辑
const edit = (row) => {
  title1.value = '编辑'
  dialogFormVisible.value = true;
  // 编辑时仅传递需要修改的字段（不含createTime）
  cwData.value = {
    id: row.id + '',
    title: row.title + '',
    intro: row.intro + '',
    briefImageUrl: row.briefImageUrl + '',
    content: row.content + '',
    counselorId: row.counselorId + '',
    del: row.del + ''
  }
}

// 确认提交
const confirm = () => {
  const submitData = {
    id: cwData.value.id,
    title: cwData.value.title,
    intro: cwData.value.intro,
    briefImageUrl: cwData.value.briefImageUrl,
    content: cwData.value.content,
    counselorId: cwData.value.counselorId,
    del: cwData.value.del || 0
    // 移除createTime，不向后端传递
  };

  const request = cwData.value.id ?
      axios.put('mindKnowledge', submitData) :
      axios.post('mindKnowledge', submitData);

  request.then((resp) => {
    if ('resp.code === 200') {
      ElMessage.success(cwData.value.id ? '修改成功' : '新增成功');
      dialogFormVisible.value = false;
      queryDataList();
    } else {
      ElMessage.error(`操作失败：${resp.message}`);
    }
  }).catch(err => {
    ElMessage.error(`请求失败：${err.message}`);
  });
};

// 删除单个
const remove = (id) => {
  if (isNaN(Number(id))) {
    ElMessage.error("无效的ID，无法删除");
    return;
  }

  ElMessageBox.confirm(
      '此操作将删除该记录, 是否继续?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios.delete(`mindKnowledge/${id}`)
        .then((resp) => {
          if ('resp.code === 200') {
            ElMessage.success('删除成功')
            queryDataList();
          } else {
            ElMessage.error('删除失败：' + resp.message)
          }
        }).catch(err => {
      ElMessage.error('删除接口请求失败：' + err.message)
    })
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}

// 批量选择
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id)
}

// 批量删除
const batchremove = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的文章')
    return
  }
  const validIds = multipleSelection.value.filter(id => !isNaN(Number(id)));
  if (validIds.length === 0) {
    ElMessage.error("选中项包含无效ID，无法删除");
    return;
  }

  ElMessageBox.confirm(
      '此操作将删除选中记录, 是否继续?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios.delete(`mindKnowledge`, {
      params: {
        ids: validIds.join(',')
      }
    })
        .then((resp) => {
          if ('resp.code === 200') {
            ElMessage.success('批量删除成功')
            queryDataList();
          } else {
            ElMessage.error('批量删除失败：' + resp.message)
          }
        }).catch(err => {
      ElMessage.error('批量删除接口请求失败：' + err.message)
    })
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}

// 详情弹窗
const detailContent = ref('');
const dialogFormVisible1 = ref(false)
const show = (content) => {
  detailContent.value = content;
  dialogFormVisible1.value = true;
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  if (response.code === 200) {
    cwData.value.briefImageUrl = response.data.url;
  }
}
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  padding: 0 0 15px;
  border-bottom: 1px solid #ddd;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-pagination-block {
  margin-top: 15px;
  text-align: right;
}

.el-table {
  line-height: 40px;
  margin-top: 15px;
}

.detail-content {
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.6;
}
</style>